package com.shkco.xbjcc.mq.consumer;

import com.shkco.exception.GlobalExceptionCode;
import com.shkco.utils.AssertUtil;
import com.shkco.xbjcc.domain.PayOrder;
import com.shkco.xbjcc.service.IAlipayInfoService;
import com.shkco.xbjcc.service.IPayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Slf4j
@Component
@RocketMQMessageListener(
        consumerGroup = "course-pay-handler-delay-group",
        topic = "course-order-handler-delay-topic",
        selectorExpression = "course-order-handler-delay-tag",
        messageModel = MessageModel.BROADCASTING
)
public class CoursePayHandlerDelayConsumer implements RocketMQListener<MessageExt> {

    @Autowired
    private IPayOrderService payOrderService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        String orderNo = new String(body, StandardCharsets.UTF_8);
        AssertUtil.isNotEmpty(orderNo, GlobalExceptionCode.ERROR);
        // 根据订单号查询支付订单
        PayOrder payOrder = payOrderService.selectByOrderNo(orderNo);
        // 判断支付订单是否存在
        if (payOrder == null){
            return;
        }
        // 判断支付状态是否为待支付
        if (PayOrder.TO_BE_PAID.equals(payOrder.getPayStatus())){
            try {
                payOrderService.cancelOrder(orderNo, payOrder);
            } catch (Exception e) {
                log.error("订单关闭失败，订单号为：{}", orderNo);
                e.printStackTrace();
            }
        }

    }
}
